﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ModelLayer;

namespace DataLayer.Infrastructure
{
    public class UnitOfWork : IDisposable
    {
        private ShopkartModel _context;
        private GenericRepo<Category> _categoryRepo;
        private GenericRepo<Order> _orderRepo;
        private GenericRepo<OrderDetail> _orderDetailRepo;
        private GenericRepo<Product> _productRepo;
        private GenericRepo<User> _userRepo;
        private GenericRepo<UserCart> _userCartRepo;

        public UnitOfWork(string dbConnectionString = "", bool isLazyLoadingEnabled = false)
        {
            //By-defalut it will point to 'SasDb' databse
            if (string.IsNullOrEmpty(dbConnectionString))
            {
                dbConnectionString = ConfigurationManager.ConnectionStrings["ShopkartConnection"].ConnectionString;
            }

            _context = new ShopkartModel(dbConnectionString, isLazyLoadingEnabled);
        }

        public GenericRepo<Category> CategoryRepo
        {
            get { return _categoryRepo ?? (_categoryRepo = new GenericRepo<Category>(_context)); }
        }
        public GenericRepo<Order> OrderRepo
        {
            get { return _orderRepo ?? (_orderRepo = new GenericRepo<Order>(_context)); }
        }

        public GenericRepo<OrderDetail> OrdeDetailRepo
        {
            get { return _orderDetailRepo ?? (_orderDetailRepo = new GenericRepo<OrderDetail>(_context)); }
        }

        public GenericRepo<Product> ProductRepo
        {
            get { return _productRepo ?? (_productRepo = new GenericRepo<Product>(_context)); }
        }

        public GenericRepo<User> UserRepo
        {
            get { return _userRepo ?? (_userRepo = new GenericRepo<User>(_context)); }
        }

        public GenericRepo<UserCart> UserCartRepo
        {
            get { return _userCartRepo ?? (_userCartRepo = new GenericRepo<UserCart>(_context)); }
        }


        public int SaveChanges()
        {
            return _context.SaveChanges();
        }

        private bool _disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    _context.Dispose();
                }
            }
            _disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}
